//
//  RGMeViewModel.m
//  RedGrass
//
//  Created by wukong on 2019/2/18.
//  Copyright © 2019年 hongcaosp. All rights reserved.
//

#import "RGMeViewModel.h"
#import "HttpRequest.h"
#import "RGMainPageRouter.h"
#import "XLMShareSdkTool.h"
#import "RGRemoteVedioDownLoadHelper.h"

#define pageSize 20

@interface RGMeViewModel()

@property (weak, nonatomic)   id<RGMeViewProtocol> protocol;
@property (strong, nonatomic) NSMutableArray *mainCommentList;//主评论列表
@property (assign, nonatomic) NSInteger mainCommentPageNum;
@property (assign, nonatomic) NSInteger mainCommentTotal;



@end

@implementation RGMeViewModel

-(instancetype) initWithProtocol:(id<RGMeViewProtocol>)protocol{
    if(self = [super init]){
        self.protocol = protocol;
        self.mainCommentPageNum = 1;
        self.mainCommentTotal = 1;
        
    }
    return self;
}

-(void)reInitProtocol{
    self.mainCommentPageNum = 1;
    self.mainCommentTotal = 0;
    self.mainCommentList = [NSMutableArray array];
}

//点赞
-(void) changeFavoriteStautswithIndexPath:(NSIndexPath *)path vedioModel:(RGRecommendVideoModel *)model{
    if(model == nil){
        return;
    }
    NSString *token = [RGUserInfoModel getUserInfo].token;
    NSInteger vedioId = model.ID;
    NSDictionary *dic = @{@"id":@(vedioId),
                          @"token":SafeStr(token)
                          };
    if(model.isLike){//当前状态是已点赞
        [self.protocol showLoading:@"正在取消点赞"];
        AA_WEAK_MAKE(self) weakSelf = self;
        HttpRequest *quest = [HttpRequest buildRequest:@"/api/userLike/cancel"];
        [quest post:dic success:^(id data) {
            [weakSelf.protocol dismissLoading];
            [weakSelf.protocol showTextMessageWithMessage:@"成功取消点赞"];
            model.isLike = NO;
            model.likeCounts = ((model.likeCounts - 1) >= 0)? (model.likeCounts - 1):0;
            if([weakSelf.protocol respondsToSelector:@selector(changeFavoriteStatusWithIsFavorite:currentCellIndex:)]){
                [weakSelf.protocol changeFavoriteStatusWithIsFavorite:NO currentCellIndex:path.row];
            }
        } fail:^(NSInteger code, NSString *message) {
            
            [weakSelf.protocol showTextMessageWithMessage:message];
        }];
    }else{
        [self.protocol showLoading:@"正在点赞"];
        AA_WEAK_MAKE(self) weakSelf = self;
        HttpRequest *quest = [HttpRequest buildRequest:@"/api/userLike/add"];
        [quest post:dic success:^(id data) {
            [weakSelf.protocol dismissLoading];
            [weakSelf.protocol showTextMessageWithMessage:@"成功点赞"];
            model.isLike = YES;
            model.likeCounts = model.likeCounts + 1;
            if([weakSelf.protocol respondsToSelector:@selector(changeFavoriteStatusWithIsFavorite:currentCellIndex:)]){
                [weakSelf.protocol changeFavoriteStatusWithIsFavorite:YES currentCellIndex:path.row];
            }
        } fail:^(NSInteger code, NSString *message) {
            
            [weakSelf.protocol showTextMessageWithMessage:message];
        }];
    }
}

//获取评论列表,更多评论,首次
-(void)gainVideoRecommentListWithIndexPath:(NSIndexPath *)path isGainMore:(BOOL)isGainMore isShowLoading:(BOOL)isShowLoading vedioModel:(RGRecommendVideoModel *)model{
    if(model == nil){
        return;
    }

    if(isGainMore){
        _mainCommentPageNum ++;
    }else{
        _mainCommentPageNum = 1;
        _mainCommentList = [NSMutableArray array];
    }
    
    NSInteger vedioId = model.ID;
    NSDictionary *dic = @{@"id":@(vedioId),
                          @"pageSize":@(pageSize),
                          @"pageNumber":@(_mainCommentPageNum)
                          };
    if(isShowLoading){
        [self.protocol showLoading:@"正在获取评论"];
    }
    AA_WEAK_MAKE(self) weakSelf = self;
    HttpRequest *quest = [HttpRequest buildRequest:@"/api/videoComments"];
    [quest post:dic success:^(id data) {

        if(isShowLoading){
            [weakSelf.protocol dismissLoading];
        }
        
        NSArray *originalArr = [data objectForKey:@"list"];
        NSError *error;
        if(originalArr.count){
            NSMutableArray *tempArr = [RGRecommentListModel arrayOfModelsFromDictionaries:originalArr error:&error];
            if(tempArr.count){
                if(isGainMore){//获取更多
                    if([weakSelf.mainCommentList count] == 0){
                        weakSelf.mainCommentList = tempArr;
                    }else{
                        [weakSelf.mainCommentList addObjectsFromArray:tempArr];
                    }
                }else{
                    weakSelf.mainCommentList = tempArr;
                }
            }
        }
        if([weakSelf.protocol respondsToSelector:@selector(reloadCommentTableViewWithCommentList:)]){
            [weakSelf.protocol reloadCommentTableViewWithCommentList:weakSelf.mainCommentList];
        }
        NSInteger total = [[data objectForKey:@"total"] integerValue];
        
        if(originalArr.count < pageSize){
            if([weakSelf.protocol respondsToSelector:@selector(changeCommentMjFooterStatusWithNoMoreData)]){
                [weakSelf.protocol changeCommentMjFooterStatusWithNoMoreData];
            }
        }
        
    } fail:^(NSInteger code, NSString *message) {
        //取消mjfresh
        if(isShowLoading){
            [weakSelf.protocol dismissLoading];
        }
        [weakSelf.protocol showTextMessageWithMessage:message];
    }];
}

//刷新评论列表
-(void) gainVideoRecommentListWithIsGainMore:(BOOL)isGainMore{
    if(_currentVideoModel == nil){
        return;
    }
   
    if(isGainMore){
        _mainCommentPageNum ++;
    }else{
        _mainCommentPageNum = 1;
        _mainCommentList = [NSMutableArray array];
    }
    NSInteger vedioId = _currentVideoModel.ID;
//    _currentVedioId = vedioId;
    NSDictionary *dic = @{@"id":@(vedioId),
                          @"pageSize":@(pageSize),
                          @"pageNumber":@(_mainCommentPageNum)
                          };
    AA_WEAK_MAKE(self) weakSelf = self;
    HttpRequest *quest = [HttpRequest buildRequest:@"/api/videoComments"];
    [quest post:dic success:^(id data) {
        
        NSArray *originalArr = [data objectForKey:@"list"];
        NSError *error;
        if(originalArr.count){
            NSMutableArray *tempArr = [RGRecommentListModel arrayOfModelsFromDictionaries:originalArr error:&error];
            if(tempArr.count){
                if(isGainMore){//获取更多
                    if([weakSelf.mainCommentList count] == 0){
                        weakSelf.mainCommentList = tempArr;
                    }else{
                        [weakSelf.mainCommentList addObjectsFromArray:tempArr];
                    }
                }else{
                    weakSelf.mainCommentList = tempArr;
                }
            }
        }
        if([weakSelf.protocol respondsToSelector:@selector(reloadCommentTableViewWithCommentList:)]){
            [weakSelf.protocol reloadCommentTableViewWithCommentList:weakSelf.mainCommentList];
        }
        NSInteger total = [[data objectForKey:@"total"] integerValue];
        if(isGainMore){
            if([weakSelf.protocol respondsToSelector:@selector(commentMjFooterEndLoading)]){
                [weakSelf.protocol commentMjFooterEndLoading];
            }
        }else{
            if([weakSelf.protocol respondsToSelector:@selector(commentMjHeaderEndLoading)]){
                [weakSelf.protocol commentMjHeaderEndLoading];
            }
        }
        
        if(weakSelf.mainCommentList.count >= total){
            if([weakSelf.protocol respondsToSelector:@selector(changeCommentMjFooterStatusWithNoMoreData)]){
                [weakSelf.protocol changeCommentMjFooterStatusWithNoMoreData];
            }
        }
        
    } fail:^(NSInteger code, NSString *message) {
        [weakSelf.protocol showTextMessageWithMessage:message];
    }];
}


//主评论点赞
-(void) changeMainCommentFavoriteStautswithChosedIndex:(NSInteger)chosedIndex{
    if(_currentVideoModel == nil || [_mainCommentList count] == 0 || chosedIndex >= _mainCommentList.count){
        return;
    }
    RGRecommentListModel *model = _mainCommentList[chosedIndex];
    NSString *token = [RGUserInfoModel getUserInfo].token;
    NSInteger commentId = model.ID;
    if(model.commentsUser.ID == [RGUserInfoModel getUserInfo].ID){//是自己的评论不能点赞
        [self.protocol showAlertWhenFarvoriteSelfComment];
        return;
    }
    NSDictionary *dic = @{@"id":@(commentId),
                          @"token":SafeStr(token)
                          };
    if(model.isLike){//当前状态是已点赞
        AA_WEAK_MAKE(self) weakSelf = self;
        HttpRequest *quest = [HttpRequest buildRequest:@"/api/comments/commentsLikeCancle"];
        [quest post:dic success:^(id data) {
            
            model.isLike = NO;
            model.likeCounts = ((model.likeCounts - 1) >= 0)? (model.likeCounts - 1):0;
            //点赞刷新UI
            if([weakSelf.protocol respondsToSelector:@selector(reloadCommentTableViewSectionWithIndex:)]){
                [weakSelf.protocol reloadCommentTableViewSectionWithIndex:chosedIndex];
            }
        } fail:^(NSInteger code, NSString *message) {
            
        }];
    }else{
        
        AA_WEAK_MAKE(self) weakSelf = self;
        HttpRequest *quest = [HttpRequest buildRequest:@"/api/comments/commentsLike"];
        [quest post:dic success:^(id data) {
            
            model.isLike = YES;
            model.likeCounts = model.likeCounts + 1;
            //点赞刷新UI
            if([weakSelf.protocol respondsToSelector:@selector(reloadCommentTableViewSectionWithIndex:)]){
                [weakSelf.protocol reloadCommentTableViewSectionWithIndex:chosedIndex];
            }
        } fail:^(NSInteger code, NSString *message) {
//            [weakSelf.protocol showTextMessageWithMessage:message];
        }];
    }
}

//子评论点赞
-(void) changeChildCommentFavoriteStautswithChosedIndex:(NSIndexPath*)path{
    if(_currentVideoModel == nil ||[_mainCommentList count] == 0 || path.section >= _mainCommentList.count){
        return;
    }
    RGRecommentListModel *model = _mainCommentList[path.section];
    
    if([model.childCommentsList count] == 0 || path.row >= [model.childCommentsList count]){
        return;
    }
    NSString *token = [RGUserInfoModel getUserInfo].token;
    RGChildRecommentListModel *childModel = model.childCommentsList[path.row];
    NSInteger childCommentId = childModel.ID;
    if(childModel.commentsUser.ID == [RGUserInfoModel getUserInfo].ID){//是自己的评论不能点赞
        [self.protocol showAlertWhenFarvoriteSelfComment];
        return;
    }
    NSDictionary *dic = @{@"id":@(childCommentId),
                          @"token":SafeStr(token)
                          };
    if(childModel.isLike){//当前状态是已点赞
        AA_WEAK_MAKE(self) weakSelf = self;
        HttpRequest *quest = [HttpRequest buildRequest:@"/api/comments/commentsLikeCancle"];
        [quest post:dic success:^(id data) {
            
            childModel.isLike = NO;
            childModel.likeCounts = ((childModel.likeCounts - 1) >= 0)? (childModel.likeCounts - 1):0;
            //点赞刷新UI
            if([weakSelf.protocol respondsToSelector:@selector(reloadCommentTableViewCellWithIndexPath:)]){
                [weakSelf.protocol reloadCommentTableViewCellWithIndexPath:path];
            }
        } fail:^(NSInteger code, NSString *message) {
            
        }];
    }else{
        
        AA_WEAK_MAKE(self) weakSelf = self;
        HttpRequest *quest = [HttpRequest buildRequest:@"/api/comments/commentsLike"];
        [quest post:dic success:^(id data) {
            
            childModel.isLike = YES;
            childModel.likeCounts = childModel.likeCounts + 1;
            //点赞刷新UI
            if([weakSelf.protocol respondsToSelector:@selector(reloadCommentTableViewCellWithIndexPath:)]){
                [weakSelf.protocol reloadCommentTableViewCellWithIndexPath:path];
            }
        } fail:^(NSInteger code, NSString *message) {
            
        }];
    }
}

//发表主评论
-(void) addMainCommentWithContent:(NSString *)content{
    if(_currentVideoModel == nil){
        return;
    }
    NSInteger vedioId = _currentVideoModel.ID;
    NSString *token = [RGUserInfoModel getUserInfo].token;
    NSDictionary *dic = @{@"id":@(vedioId),
                          @"token":SafeStr(token),
                          @"content":SafeStr(content),
                          @"type":@(0)
                          };
    AA_WEAK_MAKE(self) weakSelf = self;
    HttpRequest *quest = [HttpRequest buildRequest:@"/api/comments/replyComments"];
    [quest post:dic success:^(id data) {
        NSDictionary *dic = [data objectForKey:@"comments"];
        NSError *error;
        if([dic count]){
            RGRecommentListModel *model = [[RGRecommentListModel alloc]initWithDictionary:dic error:&error];
            if(error == nil){
                if([weakSelf.mainCommentList count] == 0){
                    weakSelf.mainCommentList = [NSMutableArray array];
                    [weakSelf.mainCommentList addObject:model];
                }else{
                    [weakSelf.mainCommentList insertObject:model atIndex:0];
                }
            }
        }
        if([weakSelf.protocol respondsToSelector:@selector(reloadCommentTableViewWithCommentList:)]){
            [weakSelf.protocol reloadCommentTableViewWithCommentList:weakSelf.mainCommentList];
        }
        if([weakSelf.protocol respondsToSelector:@selector(resetCommentStatusWhenPublicSuccess)]){
            [weakSelf.protocol resetCommentStatusWhenPublicSuccess];
        }
        [weakSelf updateVedioCommentCountWhenpublishCommentSuccess];
    } fail:^(NSInteger code, NSString *message) {
        NSLog(@"");
    }];
}

-(NSInteger)getAllCommentCount {
    NSInteger count = _mainCommentList ? _mainCommentList.count : 0;
    if (count > 0) {
        for (RGRecommentListModel *model in _mainCommentList) {
            count += model.childCommentsList ? model.childCommentsList.count : 0;
        }
    }
    return count;
}

//主评论发表成功后,刷新对应视频的评论的评论数
-(void) updateVedioCommentCountWhenpublishCommentSuccess{
    
    _currentVideoModel.commentsCounts = [self getAllCommentCount];
    if([self.protocol respondsToSelector:@selector(updateCommentCountsWhenCommentSuccessWithCellIndex:)]){
        [self.protocol updateCommentCountsWhenCommentSuccessWithCellIndex:0];
    }
}

//发表子评论
-(void) addChildCommentWithContent:(NSString *)content chosedIndexPath:(NSIndexPath *)path chosedIndex:(NSInteger)chosedIndex{
    if(_currentVideoModel == nil){
        return;
    }
    NSInteger vedioId = _currentVideoModel.ID;
    RGRecommentListModel *model;
    NSInteger commentId;
    NSInteger commentUserId;
    if(path == nil){//点击主评论发表子评论
        model = _mainCommentList[chosedIndex];
        if(model == nil){
            return;
        }
        commentId = model.ID;
        commentUserId = model.commentsUser.ID;
    }else{
        model = _mainCommentList[path.section];
        RGRecommentListModel *childModel = model.childCommentsList[path.row];
        if(childModel == nil){
            return;
        }
        commentId = childModel.ID;
        commentUserId = childModel.commentsUser.ID;
        
    }
    NSString *token = [RGUserInfoModel getUserInfo].token;
    RGUserInfoModel *user = [RGUserInfoModel getUserInfo];
    if(user.ID == commentUserId){
        [self.protocol showAlertWhenCommentSelfComment];
        return;
    }
    
    NSDictionary *dic = @{@"id":@(vedioId),
                          @"token":SafeStr(token),
                          @"content":SafeStr(content),
                          @"type":@(0),
                          @"commentsId":@(commentId)
                          };
    AA_WEAK_MAKE(self) weakSelf = self;
    HttpRequest *quest = [HttpRequest buildRequest:@"/api/comments/replyComments"];
    [quest post:dic success:^(id data) {
        NSDictionary *dic = [data objectForKey:@"comments"];
        NSError *error;
        if([dic count]){
            RGChildRecommentListModel *childModel = [[RGChildRecommentListModel alloc]initWithDictionary:dic error:&error];
            if(error == nil){
                if([model.childCommentsList count] == 0){
                    model.childCommentsList = [@[childModel] mutableCopy];
                }else{
                    [model.childCommentsList insertObject:childModel atIndex:0];
                }
            }
        }
        if([weakSelf.protocol respondsToSelector:@selector(reloadCommentTableViewWithCommentList:)]){
            [weakSelf.protocol reloadCommentTableViewWithCommentList:weakSelf.mainCommentList];
        }
        if([weakSelf.protocol respondsToSelector:@selector(reloadCommentTableViewSectionWithIndex:)]){
            [weakSelf.protocol reloadCommentTableViewSectionWithIndex:path.section];
        }
        if([weakSelf.protocol respondsToSelector:@selector(resetCommentStatusWhenPublicSuccess)]){
            [weakSelf.protocol resetCommentStatusWhenPublicSuccess];
        }
        [weakSelf updateVedioCommentCountWhenpublishCommentSuccess];
    } fail:^(NSInteger code, NSString *message) {
        NSLog(@"");
    }];
}

//转发视频
-(void) shareVideoWithContent:(NSString *)content chosedIndex:(NSInteger)index{
    if(_currentVideoModel == nil){
        return;
    }
   
    NSString *token = [RGUserInfoModel getUserInfo].token;
    NSDictionary *dic = @{@"id":@(_currentVideoModel.ID),
                          @"token":SafeStr(token),
                          @"content":SafeStr(content)
                          };
    AA_WEAK_MAKE(self) weakSelf = self;
    HttpRequest *quest = [HttpRequest buildRequest:@"/api/videos/videosForward"];
    [self.protocol showLoading:@""];
    [quest post:dic success:^(id data) {
        [weakSelf.protocol dismissLoading];
        [weakSelf.protocol showTextMessageWithMessage:@"转发成功"];
        if([weakSelf.protocol respondsToSelector:@selector(dismissToolBarView)]){
            [weakSelf.protocol dismissToolBarView];
        }
        [weakSelf updateShareVedioCountWhenShareSuccessWithchosedIndex:index];
    } fail:^(NSInteger code, NSString *message) {
        [weakSelf.protocol dismissLoading];
        [weakSelf.protocol showTextMessageWithMessage:message];
    }];
}
//转发成功后更新vedio的转发次数
-(void) updateShareVedioCountWhenShareSuccessWithchosedIndex:(NSInteger)index{
    if(_currentVideoModel == nil){
        return;
    }
   
    _currentVideoModel.forwardCounts = _currentVideoModel.forwardCounts + 1;
    if([self.protocol respondsToSelector:@selector(updateforwardCountsWhenShareSuccessWithCellIndex:)]){
        [self.protocol updateforwardCountsWhenShareSuccessWithCellIndex:index];
    }
}

//跳转到聊天界面
-(void) pushToChatVcWithChosedVedioIndex:(NSInteger)index{
    if(_currentVideoModel == nil){
        return;
    }
    NSInteger userId = [RGUserInfoModel getUserInfo].ID;
    if(userId == _currentVideoModel.videoUser.ID){
        [self.protocol showTextMessageWithMessage:@"不能和自己发私信"];
    }else{
        [RGMainPageRouter pushToLoginWithPassViewControllerFromVC:(UIViewController *)self.protocol userId:userId toUserId:_currentVideoModel.videoUser.ID nickName:_currentVideoModel.videoUser.nickname];
    }
}

//跳转到个人信息页面
-(void) pushToPersonalVcWithChosdeVedioIndex:(NSInteger)index{
    if(_currentVideoModel == nil){
        return;
    }
    AA_WEAK_MAKE(self)weakSelf = self;
    void (^FoucsChangedBlock)(BOOL) = ^(BOOL isFoucs){
        
//        _currentVideoModel.videoUser.meFollowmTa = isFoucs;
//        if([weakSelf.protocol respondsToSelector:@selector(changeFocusStatusWithIsFocus:currentCellIndex:)]){
//            [weakSelf.protocol changeFocusStatusWithIsFocus:isFoucs currentCellIndex:index];
//        }
    };
   
    [RGMainPageRouter pushToPersonInfoViewControllerFromVC:(UIViewController *)self.protocol userId:_currentVideoModel.videoUser.ID meFollowTa:_currentVideoModel.videoUser.meFollowmTa nickName:_currentVideoModel.videoUser.nickname focusChangedBlock:FoucsChangedBlock];
}

//分享
-(void) shareToWeChatWithChosedVedioIndex:(NSInteger)index{
    if(_currentVideoModel == nil){
        return;
    }
   
    [XLMShareSdkTool shareVedioWithPlatformType:SSDKPlatformTypeWechat Text:_currentVideoModel.videoDesc title:@"红草视界" url:_currentVideoModel.videoPath thumbImage:IMAGE_NAMED(@"icon1") image:nil musicFileURL:nil extInfo:nil fileData:nil emoticonData:nil sourceFileExtension:nil sourceFileData:nil type:SSDKContentTypeVideo onStateChanged:^(SSDKResponseState state) {
        
    }];
    
}

//下载视频
-(void) downLoadVedioWithChosedVedioIndex:(NSInteger)index{
    if(_currentVideoModel == nil){
        return;
    }
    
    [[RGRemoteVedioDownLoadHelper downLoadhepler] downLoadRemoteVedioWithUrl:_currentVideoModel.videoPath];
}

//更新视频播放量
-(void) updateVeidoPlayCountsWithChosedVedioId:(NSInteger)ID{
    if(ID <= 0){
        return;
    }
    HttpRequest *quest = [HttpRequest buildRequest:@"/api/playCount"];
    [quest post:@{@"id":@(ID)} success:^(id data) {
        NSLog(@"更新成功");
    } fail:^(NSInteger code, NSString *message) {
        
    }];
}


@end
